//
//  OAuthViewController.swift
//  SinaWeiBo
//
//  Created by dengchen on 15/11/10.
//  Copyright © 2015年 name. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    
    @objc private func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fullAccount() {
        let jsString = "document.getElementById('userId').value = 'leiggee@126.com' , document.getElementById('passwd').value = 'oyonomg';"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        view = webView
        setupUI()
        loadWebView()
    }

    let webView = UIWebView()
    
    private func loadWebView() {
        
        let url = UserAccountOAuthModel().oauthURL()

        webView.delegate = self
        webView.loadRequest(NSURLRequest(URL:url))

    }
    
    
    
    private func setupUI() {
    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
        
    }
    



}

//MARK: webViewDelegate

extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus(MessageTipLoading)
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        if error?.code == 102 {
            SVProgressHUD.dismiss()
        } else {
            SVProgressHUD.showInfoWithStatus(MessageTipError)
        }
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //协议方法 如果返回 bool  一般表示 如果为true  表示当前对象可以正常 工作  否则就不能
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.URL?.absoluteString.hasPrefix(UserAccountOAuthModel().redirectUri) == false {
            return true
        }
        
        if let query = request.URL?.query{
            
            if query.hasPrefix("code="){
                
                let code = query.substringFromIndex("code=".endIndex)
                
            UserAccountOAuthModel.shared.loadAccessToken(code, finished: { (error) -> () in
                if error != nil {
                    print(error)
                    return
                }
                
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        
                        UIApplication.sharedApplication().keyWindow?.rootViewController = WellComeViewController()
                    })
                
               })
                
                return false
            }
        }
        
        print(request.URL)
     
        return false
    }
}



//
//Optional(https://api.weibo.com/oauth2/authorize?client_id=1407267207&redirect_uri=http://www.baidu.com)
//    Optional(https://api.weibo.com/oauth2/authorize)
//        Optional(https://api.weibo.com/oauth2/authorize#)
//            Optional(https://api.weibo.com/oauth2/authorize)
//                Optional(http://www.baidu.com/?code=00d0b3b9ad2b4813ce8d8c81a38b6ffb)
//                    Optional(https://m.baidu.com/?code=00d0b3b9ad2b4813ce8d8c81a38b6ffb&from=844b&vit=fps)
//                        Optional(about:blank)












